<?php
    function savePendingOrder($httpParsedResponseAr){
        $order_date = date('d/m/Y H:i:s');
        $Amount     = urldecode($httpParsedResponseAr["PAYMENTREQUEST_0_AMT"]);
        $token      = urldecode($httpParsedResponseAr["TOKEN"]);
        $payerid    = urldecode($httpParsedResponseAr["PAYERID"]);
        $status      = 'P'; //pending
        
        $statement = "INSERT INTO x2_orders (order_date, order_amount, token, payerid, status) values('$order_date','$Amount','$token','$payerid','$status')";
        
        dump($statement);
        mysql_query($statement);
        
        return mysql_insert_id();
    }
    
    function savePendingOrderCC($total_amount, $sh_amount, $token, $payerid, $expiration, $cvv){
        $order_date = date('d/m/Y H:i:s');
        $status      = 'P'; //pending
        
        $statement = "INSERT INTO x2_orders (order_date, order_amount, sh_amount, token, payerid, status, expiration, verifycode)".
        " values('$order_date','$total_amount','$sh_amount','$token','$payerid','$status', '$expiration' ,'$cvv')";
        
        dump($statement);
        mysql_query($statement);
        
        return mysql_insert_id();
    }

	
	function saveOrderDetails($orderid){
            $orderdetails_stm = "INSERT INTO x2_orderdetails (orderid, pid, quantity, unit_price, discount, type) values ";
            for($i = 0 ; $i < count($_SESSION['cart']) ; $i++){
                $fred = intval($_SESSION['cart'][$i]['shipfreq']);
                $pid	 	= $_SESSION['cart'][$i]['productid'];
                $qty 		= intval($_SESSION['cart'][$i]['qty'])/$fred;
                $unit_price = get_price($pid);			
                $discount   = intval($_SESSION['cart'][$i]['discount']); 

                $orderdetails_stm .= "('$orderid','$pid','$qty','$unit_price','$discount', '$fred'),"; 
            }

            $orderdetails_stm = substr($orderdetails_stm, 0, -1);		

            dump($orderdetails_stm);
            $result = mysql_query($orderdetails_stm);
            return $result;		
	}
	
	function updateOrder($orderid, $txnum){
            $result = mysql_query("update x2_orders set status='C', txnum='$txnum' where orderid=$orderid");
            return $result;
	}
        
        function updateOrderCC($orderid, $txnum, $token){
            $result = mysql_query("update x2_orders set status='C', txnum='$txnum', token='$token' where orderid=$orderid");
            return $result;
	}
	
	function login($username, $pwd){
            $result = mysql_query("select * from x2_users where email='$username' and password='$pwd'");
            return (mysql_num_rows($result) > 0);
        }
        function loginByEmail($username, $pwd){
            $result = mysql_query("select * from x2_users where email='$username' and password='$pwd'");
            return $result;
        }
	
        function isUserExist($email){
            $result = mysql_query("select * from x2_users where email='$email'");
            return (mysql_num_rows($result) > 0);
        }
        
        function getFullName($email){
            $result = mysql_query("select firstname, lastname from x2_users where email='$email'");
            $row = mysql_fetch_array($result);
            return $row['firstname']." ".$row['lastname'];
        }
        
        function resetpwd($email, $pwd){
            $result = mysql_query("update x2_users set password='$pwd' where email='$email'");
            return $result;
        }

	function isTrialExist($email){
            $result = mysql_query("select * from x2_freetrial where email='$email'");
            return (mysql_num_rows($result) > 0);
        }	
			
	function saveTrialUser($email){
            $statment = "INSERT INTO x2_freetrial (email, trial_date, count) values('$email',now(),'1')";
            dump($statment);
            $result = mysql_query($statment);                        
            return $result;
        }
	
	function saveNewUser($username, $pwd, $name, $email, $phone, $address1, $address2, $city, $state, $postalcode, $country, $shipfname, $shiplname, $shipAddress1, $shipAddress2, $shipCity, $shipState, $shipPostalcode, $shipPhone, $shipCountry){
		$statment = "INSERT INTO x2_users (firstname, password, lastname, email, phone, address1, address2, city, state, postalcode, country, shipfirstname, shiplastname, shipaddress1, shipaddress2, shipcity, shipstate, shippostalcode, shipphone, shipcountry) ".
                                        "values('$username','$pwd','$name','$email','$phone','$address1','$address2','$city','$state','$postalcode','$country', '$shipfname', '$shiplname', '$shipAddress1', '$shipAddress2', '$shipCity', '$shipState', '$shipPostalcode', '$shipPhone', '$shipCountry')";
		dump($statment);
		$result = mysql_query($statment);                        
		return $result;
    }
    
    function saveNewShipAddress($orderid, $email, $billfname, $billlname, $billphone, $billaddress1, $billaddress2, $billcity, $billstate, $billpostalcode, $billcountry,
                                    $shipfname, $shiplname, $shipAddress1, $shipAddress2, $shipCity, $shipState, $shipPostalcode, $shipPhone, $shipCountry){
        $statment = "INSERT INTO x2_billaddress (orderid, email, billfirstname, billlastname, billphone, billaddress1, billaddress2, billcity, billstate, billpostalcode, billcountry) ".
                                    "values('$orderid', '$email', '$billfname', '$billlname', '$billphone', '$billaddress1', '$billaddress2', '$billcity', '$billstate', '$billpostalcode', '$billcountry')";
        dump($statment);
        $result = mysql_query($statment);
        
        $statment = "INSERT INTO x2_shipaddress (orderid, shipfirstname, shiplastname, shipaddress1, shipaddress2, shipcity, shipstate, shippostalcode, shipphone, shipcountry) ".
                "values('$orderid', '$shipfname','$shiplname', '$shipAddress1', '$shipAddress2', '$shipCity', '$shipState', '$shipPostalcode', '$shipPhone', '$shipCountry')";
        dump($statment);
        $result = mysql_query($statment);                                
        return $result;
    }
	
    function get_product_name($pid){
		$result=mysql_query("select product_name from x2_products where id=$pid");
		$row=mysql_fetch_array($result);
		return $row['product_name'];
	}
    function get_product_desc($pid){
		$result=mysql_query("select short_desc, price, full_desc from x2_products where id=$pid");
		$row=mysql_fetch_array($result);
		return $row['short_desc'].' - $<b>'.$row['price'].'</b> + shipping &amp; handling '. str_replace('</br>','',$row['full_desc']);
	}
	 function get_product_short_desc($pid){
		$result = mysql_query("select short_desc, price, full_desc from x2_products where id=$pid");
		$row = mysql_fetch_array($result);
		return $row['short_desc'];
	}
	function get_product_thumb($pid){
		$result = mysql_query("select short_desc, price, full_desc, thumb_img_url from x2_products where id=$pid");
		$row = mysql_fetch_array($result);
		return $row['thumb_img_url'];
	}
	function get_price($pid){
		$result=mysql_query("select price from x2_products where id=$pid");
		$row=mysql_fetch_array($result);
		return $row['price'];
	}
	
	function get_discount($qty){
		$ret = 0;
		
		if($qty > 2){
			if($qty < 6){
				$ret = 10;	/*3-5 cases $139.95 + shipping & handling*/
			}else{
				$ret = 20; /*6+ cases $129.95 + shipping & handling*/
			}
		}
		
		return $ret;		
	}
        
        function get_sh($pid){
            $result=mysql_query("select ship_amt from x2_shippingfee where product_type=$pid");
            $row=mysql_fetch_array($result);
            return $row['ship_amt'];
            
            /*    
            if($pid == 1){
                return 7.95;
            }elseif ($pid == 2) {
                return 14.95;    
            }elseif ($pid == 3) {
                return 7.95;    
            }else{
                return 14.95;
            }
            */
        }
	
	function remove_product($pid){
		$pid=intval($pid);
		$max=count($_SESSION['cart']);
		for($i=0;$i<$max;$i++){
			if($pid==$_SESSION['cart'][$i]['productid']){
				unset($_SESSION['cart'][$i]);
				break;
			}
		}
		$_SESSION['cart']=array_values($_SESSION['cart']);
	}
        
	function get_order_total(){
            $sum = 0;
            if(isset($_SESSION['cart']) && is_array($_SESSION['cart'])){    
		$max = count($_SESSION['cart']);	
		for($i=0; $i<$max; $i++){
                    $fred = intval($_SESSION['cart'][$i]['shipfreq']);
                    $pid = $_SESSION['cart'][$i]['productid'];
                    $q = $_SESSION['cart'][$i]['qty'];
                    $price = get_price($pid);
                    $sum += $price*$q/$fred;
		}
            }
		return $sum;
	}
        
        function get_case_plan($pid){
            $fred = 1;
            if(isset($_SESSION['cart']) && is_array($_SESSION['cart'])){    
		$max = count($_SESSION['cart']);	
		for($i=0; $i<$max; $i++){
                    
                    if($_SESSION['cart'][$i]['productid'] == $pid){
                        $fred = intval($_SESSION['cart'][$i]['shipfreq']);
                        break;
                    }
                    
		}
            }
		return $fred;
	}

	function get_sh_total(){
            $sum = 0;
            if(isset($_SESSION['cart']) && is_array($_SESSION['cart'])){    
		$max = count($_SESSION['cart']);	
		for($i=0; $i<$max; $i++){
                    $fred = intval($_SESSION['cart'][$i]['shipfreq']);
                    $pid = $_SESSION['cart'][$i]['productid'];
                    $q = $_SESSION['cart'][$i]['qty'];
                    $price = get_sh($pid);
                    $sum += ($price*$q)/$fred;
		}
            }
		return $sum;
	}        
        
        function get_discount_total(){
            $sum = 0;
            if(isset($_SESSION['cart']) && is_array($_SESSION['cart'])){    
		$max = count($_SESSION['cart']);	                
                
		for($i=0; $i<$max; $i++){
                    $fred = intval($_SESSION['cart'][$i]['shipfreq']);			
                    $q = $_SESSION['cart'][$i]['qty'];			
                    $discount = intval($_SESSION['cart'][$i]['discount']);
                    if($discount > 0){
                        $sum += $discount*$q/$fred;
                    }
		}
            }
		return $sum;
	}
        
	function addtocart($pid, $q, $discount = 0, $shipfreq = 1){
		if($pid<1 or $q<1) return;
		
		if(is_array($_SESSION['cart'])){
			if(product_exists($pid)) return;
			$max=count($_SESSION['cart']);
			$_SESSION['cart'][$max]['productid']=$pid;
			$_SESSION['cart'][$max]['qty']=$q;
			$_SESSION['cart'][$max]['discount']=$discount;
                        $_SESSION['cart'][$max]['shipfreq']=$shipfreq;
		}
		else{
			$_SESSION['cart']=array();
			$_SESSION['cart'][0]['productid']=$pid;
			$_SESSION['cart'][0]['qty']=$q;
			$_SESSION['cart'][0]['discount']=$discount;
                        $_SESSION['cart'][0]['shipfreq']=$shipfreq;
		}
	}
        
	function product_exists($pid){
		$pid=intval($pid);
		$max=count($_SESSION['cart']);
		$flag=0;
		for($i=0;$i<$max;$i++){
			if($pid==$_SESSION['cart'][$i]['productid']){
				$flag=1;
				break;
			}
		}
		return $flag;
	}
	
	function dump($stringData){
		$myFile = LOG_PATH;
		$now = date('d/m/Y H:i:s');
		$fh = fopen($myFile, 'a') or die("can't open file " . LOG_PATH);
		fwrite($fh, "[$now]: $stringData\n");
		fclose($fh);	
	}	
	
	function isValidEmail($email){
            return preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $email);
	}
        
        function generate_password($length = 10){
            $chars =  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

            $str = '';
            $max = strlen($chars) - 1;

            for ($i=0; $i < $length; $i++)
                $str .= $chars[rand(0, $max)];

            return $str;
        }               
        
        function notifyOrder($url, $fields){                        

            //open connection
            $ch = curl_init();
            //set the url, number of POST vars, POST data
            curl_setopt($ch, CURLOPT_HEADER, 0);        
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
            //execute post
            try {
                $result = curl_exec($ch);
                if ($result['curl_error'])    throw new Exception($result['curl_error']);
                if ($result['http_code']!='200')    throw new Exception("HTTP Code = ".$result['http_code']);                
            } catch (Exception $e) {
                dump($e->getMessage());
            }

            //close connection
            curl_close($ch);               
        }
?>